package com.guslegend.service.impl;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.guslegend.config.OSSConfig;
import com.guslegend.service.FileService;
import com.guslegend.utils.CommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
@Slf4j
public class FileServiceImpl implements FileService {

    @Autowired
    private OSSConfig ossConfig;

    @Override
    public String uploadUserImg(MultipartFile file) {

        //获取相关配置
        String bucketName=ossConfig.getBucketName();
        String endpoint = ossConfig.getEndpoint();
        String accessKeySecret = ossConfig.getAccessKeySecret();
        String accessKeyId = ossConfig.getAccessKeyId();
        //创建oss对象
        OSS ossClient=new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);

        //获取原生文件 xxx.jpg
        String originalFileName=file.getOriginalFilename();
        //JDK8的日期格式
        LocalDateTime ldt=LocalDateTime.now();
        DateTimeFormatter dtf=DateTimeFormatter.ofPattern("yyyy/MM/dd");

        //拼装路径,oss上存储的路径  user/2025/6/9 asdakfdhjak.jpg
        String folder=dtf.format(ldt);
        String fileName= CommonUtils.generateUUID();
        String extension=originalFileName.substring(originalFileName.lastIndexOf("."));

        //在oss上的bucket下创建user这个文件夹
        String newFileName = "user/" + folder + "/" + fileName + extension;
        try {
            PutObjectResult putObjectRequest=ossClient.putObject(bucketName,newFileName,file.getInputStream());
            //拼装放回路径
            if (putObjectRequest!=null){
                String imgUrl="https://"+bucketName+"."+endpoint+"/"+newFileName;
                return imgUrl;
            }
        } catch (IOException e) {
            log.error("文件上传失败:{}",e);
        }finally {
            //关闭oss服务,不然会造成OOM
            ossClient.shutdown();
        }
        return null;
    }
}
